#include "register.h"
#include "ui_register.h"
#include<QTcpSocket>
#include <QMessageBox>
#include <QHostInfo>
Register::Register(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
    //绑定接收的函数
    tcpClient=new QTcpSocket(this);
    QString LocalIP=getLocalIP();
    //连接服务器
    quint16 targetport=8888;
    tcpClient->connectToHost(LocalIP,targetport);
    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
}

Register::~Register()
{
    delete ui;
}

QString Register::getLocalIP()
{
    QString hostName=QHostInfo::localHostName();
    QHostInfo hostInfo=QHostInfo::fromName(hostName);
    QString localIP="";
    QList<QHostAddress> addList=hostInfo.addresses();
    if(!addList.isEmpty())
    {
        for(int i=0;i<addList.count();i++)
        {
            QHostAddress aHost=addList.at(i);
            if(QAbstractSocket::IPv4Protocol==aHost.protocol())
            {
                localIP=aHost.toString();
                break;
            }
        }
    }
    return localIP;
}

void Register::on_submit_pushButton_clicked()
{
    //提交注册的信息
    QByteArray data;//因为信息的修改发生在接收信号的机器上，所以需要将这些信息传过去
    QDataStream out(&data, QIODevice::WriteOnly);
    QString username=ui->username_lineEdit->text();
    int sex=ui->sex_comboBox->currentIndex();//0:男；1：女
    QString password=ui->password_lineEdit->text();
    QString contry=ui->contry_lineEdit->text();
    QString province=ui->province_lineEdit->text();
    QString city=ui->city_lineEdit->text();
    QString signature=ui->signature_textEdit->toPlainText();
    out<< quint8('R')<<username<<sex<<password<<contry<<province<<city<<signature;
    tcpClient->write(data);//发送数据




}

void Register::processPendingDatagrams()//接收服务器发回的消息
{
    QByteArray datagram;
    datagram=tcpClient->readAll();
    QDataStream in(&datagram,QIODevice::ReadOnly);
    quint8 type;
    QString info;
    in>>type;
    //提交成功,回到登录界面
    if(type=='S')
    {
        QMessageBox::information(0,tr("提示"),tr("注册成功"),QMessageBox::Ok);
        this->close();
    }
    else if(type=='F') //提交信息有误，名字被占用了
    {
         in>>info;
         QMessageBox::warning(0,tr("警告"),"名称已被占用"+info,QMessageBox::Ok);
    }
    else if(type=='D')//数据库出错
    {
         in>>info;
         QMessageBox::warning(0,tr("警告"),"数据库出错"+info,QMessageBox::Ok);
    }
    else
    {
        QMessageBox::warning(0,tr("警告"),"未知错误"+info,QMessageBox::Ok);
    }


}

